package com.zl.autocode.service.generator.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zl.autocode.common.constant.AutocodeConfigC;
import com.zl.autocode.dao.generator.GeneratorSqlDao;
import com.zl.autocode.dto.generator.ReqSqlQueryDTO;
import com.zl.autocode.dto.generator.ResSqlQueryDTO;
import com.zl.autocode.entity.autocode.ZlProject;
import com.zl.autocode.service.base.AutocodeBaseManager;
import com.zl.autocode.service.generator.IGeneratorSqlService;
import com.zl.common.dto.ReqDTO;
import com.zl.common.dto.pagination.PageReqVO;
import com.zl.common.enums.resp.GlobalRespEnum;
import com.zl.common.exception.BizException;
import com.zl.config.mybatis.MapString;

import cn.hutool.db.ds.simple.SimpleDataSource;

/**
 * 在线SQL
 * @author ZL
 */
@Service("autocodeGeneratorSqlService")
public class GeneratorSqlServiceManager extends AutocodeBaseManager implements IGeneratorSqlService {

    private static Logger LOGGER = LoggerFactory.getLogger(GeneratorSqlServiceManager.class);
    
    @Autowired
    protected GeneratorSqlDao generatorSqlDao;
    @Autowired
    protected DataSource dynamicDataSource;
    
    @Override
    public ResSqlQueryDTO querySqlResult(ReqDTO<ReqSqlQueryDTO> reqInfo,ZlProject projectInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqSqlQueryDTO reqData = reqInfo.getReqData();
        ResSqlQueryDTO resDTO = new ResSqlQueryDTO();
        
        Map<String,Object> params = new HashMap<>();
        
        PageReqVO page = pageHandle(reqInfo.getPageInfo());//处理分页数据
        
        String cdskey = AutocodeConfigC.DDS_KEY + reqData.getProjectId().toString();
        try{
            DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource)dynamicDataSource;
            if(dynamicRoutingDataSource.getDataSources().get(cdskey)!=null){
                DynamicDataSourceContextHolder.push(cdskey);
            }
            else if(StringUtils.isNotBlank(projectInfo.getJdbcUrl()) && StringUtils.isNotBlank(projectInfo.getJdbcLoginname())){
                SimpleDataSource dynamicDataSourceVO = new SimpleDataSource(projectInfo.getJdbcUrl(), projectInfo.getJdbcLoginname(), projectInfo.getJdbcPassword());
                dynamicDataSourceVO.setLoginTimeout(30);
                dynamicRoutingDataSource.addDataSource(cdskey, dynamicDataSourceVO);
                DynamicDataSourceContextHolder.push(cdskey);
            }
        }catch(Exception e){
            LOGGER.error("数据库连接异常{}",e);
            throw new BizException(GlobalRespEnum.DATABASE_CONNECT_FAILED);
        }
        
        try{
            params.clear();
            params.put("sqlStr", reqData.getSqlStr());
            
            Page<Object> pageHp = null;
            if("hive2".equals(projectInfo.getDatabaseType())){//不分页
                pageHp = PageHelper.startPage(page.getPage(), page.getLimit());
                pageHp.setDialectClass("mysql");
            }else{
                pageHp = PageHelper.startPage(page.getPage(), page.getLimit());
            }
            List<MapString<String, Object>> result = generatorSqlDao.selectResultByDiySql(reqData.getSqlStr());
            
            List<Map<String, Object>> list =  new ArrayList<>();;
            List<String> fields = new ArrayList<>();
            if(result!=null && result.size()>0){
                for(Entry<String, Object> x:((Map<String, Object>)result.get(0)).entrySet()){
                    fields.add(x.getKey());
                }
                for(Map<String, Object> x:result){
                    list.add(x);
                }
            }
            resDTO.setList(list);
            resDTO.setTotal(pageHp.getTotal());
            resDTO.setFields(fields);
        }catch(Exception e){
            LOGGER.error("数据库查询异常{}",e);
            throw new BizException(GlobalRespEnum.ERROR.getMsg(),e.getMessage());
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
        
        return resDTO;
    }
}